package com.palazzisoft.railsystem.model;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @author pablo
 *
 */
public class Net<T , E> {

	private Map<T,HashSet<T>> adjacents;
	private Map<Pair<T,T>, E> segments;
	
	public Net() {
		this.adjacents = new HashMap<T, HashSet<T>>();
		this.segments = new HashMap<Pair<T,T>, E>();		
	}
	
	public int getSegmentsCounts() {
		return this.segments.size();
	}
	
	public boolean addSegment(T from, T to, E value) {
		if (!from.equals(to)) {
			Pair<T,T> newSegment = new Pair<T,T>(from, to);
			this.segments.put(newSegment, value);
			this.adjacents.put(from, addPair(from, to));
			
			return true;
		}

		return false;		
	}
	
	public boolean exist(T from, T to) {
		Pair<T,T> pair = new Pair<T,T>(from, to);
		
		return this.segments.containsKey(pair);
	}
	
	public E valueOf(T from, T to) {
		if (exist(from, to)) {
			Pair<T,T> pair = new Pair<T,T>(from, to);
			return this.segments.get(pair);
		}
		
		return null;
	}
	
	public Set<T> getAdjacentsFrom(T from) {
		return this.adjacents.get(from);
	}
	
	public Set<T> getAllSegments() {
		Set<T> segments = new HashSet<T>();
		
		if (!this.segments.isEmpty()) {
			for (Pair<T,T> pair : this.segments.keySet()) {
				segments.add(pair.getFirst());
			}
		}
		
		return segments;
	}
	
	private HashSet<T> addPair(T from, T to) {
		if (this.adjacents.get(from) == null) {
			HashSet<T> set = new HashSet<T>();
			set.add(to);
			
			return set;
		}
		
		this.adjacents.get(from).add(to);		
		return this.adjacents.get(from);
	}

	public Map<T, HashSet<T>> getAdjacents() {
		return adjacents;
	}

	public Map<Pair<T,T>, E> getSegments() {
		return this.segments;
	}	
 }
